package com.itheima.service.mongo.yuyin;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.RecommendVideo;
import com.itheima.domain.mongo.yuyin.Sound;
import com.itheima.service.mongo.impl.RedisIdService;
import com.itheima.util.ConstantUtil;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class SoundServiceImpl implements SoundService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    RedisIdService redisIdService;

    @Override
    public void save(Sound sound) {
        //0.给video设置vid
        sound.setVid(redisIdService.getNextId(ConstantUtil.VIDEO_ID));

        mongoTemplate.save(sound);

    }

    @Override
    public Sound findBySound(String gender) {

        Query query = new Query();

        if ("man".equals(gender)) {

            query.addCriteria(Criteria.where("gender").is("woman"));

        }
        if ("woman".equals(gender)) {

            query.addCriteria(Criteria.where("gender").is("man"));

        }

        List<Sound> sounds = mongoTemplate.find(query, Sound.class);

        if (CollUtil.isNotEmpty(sounds)) {
            int size = sounds.size();
            if (size==0) {
                size=size+1;
            }

            int randomInt = RandomUtil.randomInt(0, size);
            return sounds.get(randomInt);
        }


        List<Sound> soundList = mongoTemplate.findAll(Sound.class);

        if (CollUtil.isNotEmpty(soundList)) {

            int size = soundList.size();
            if (size==0) {
                size=size+1;
            }

            int randomInt = RandomUtil.randomInt(0, size);
            return soundList.get(randomInt);

        }


        return null;
    }
}
